package com.zhaofujun.filequeue;

import java.util.concurrent.atomic.AtomicReference;

public class WriteNumRef {
    private final AtomicReference<WriteInfo> writeNumAtomicReference = new AtomicReference<>();


    public WriteNumRef(long num, long offset) {
        this.writeNumAtomicReference.set(new WriteInfo(num, offset));
    }

    public WriteInfo getAndSet(int bytesLength, SegmentFileMapper segmentContext) {
        WriteInfo writeInfo = writeNumAtomicReference.get();
        WriteInfo newWriteInfo;

        SegmentInfo segmentInfo = segmentContext.calculateSegmentInfo(writeInfo.getNum() + 1);
        if (segmentInfo.getIndex() == 0) {
            newWriteInfo = new WriteInfo(segmentInfo.getPosition(), segmentContext.calculateFirstOffset());
        } else {
            newWriteInfo = new WriteInfo(segmentInfo.getPosition(), writeInfo.getOffset() + bytesLength);
        }
        if (writeNumAtomicReference.compareAndSet(writeInfo, newWriteInfo)) {
            return writeInfo;
        }
        return getAndSet(bytesLength, segmentContext);
    }

    public WriteInfo getNumRef() {
        return writeNumAtomicReference.get();
    }

    public long getNum() {
        return writeNumAtomicReference.get().getNum();
    }

}
